package org.jeecg.modules.zhouAdmin.admin.orderFactory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.degression.mapper.MyMlccPaidanOrderGongyiMapper;
import org.jeecg.modules.degression.pojo.MlccPaidanOrderGongyi;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.mapper.MySysUserMapper;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.pojo.MySysUser;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.MyMlccPaidanOrderAfterMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.MyMlccPaidanOrderCostMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.MyMlccSysuserOrderInfoMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MlccPaidanOrderAfter;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MlccPaidanOrderCost;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MlccSysuserOrderInfo;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.service.IOrderCenterService;
import org.jeecg.modules.zhouAdmin.admin.orderFactory.mapper.OrderFactoryMapper;
import org.jeecg.modules.zhouAdmin.admin.orderFactory.service.IOrderFactoryService;
import org.jeecg.modules.zhouAdmin.admin.util.SingleAndTeamOrderUtil;
import org.jeecg.modules.zhoupackage.mapper.*;
import org.jeecg.modules.zhoupackage.pojo.*;
import org.jeecg.modules.zhoupackage.pojo.myexcel.MyteamPriceProduct;
import org.jeecg.modules.zhoupackage.util.FabricUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 工厂订单
 */
@Service
public class OrderFactoryServiceImpl implements IOrderFactoryService {

    @Autowired
    OrderFactoryMapper orderFactoryMapper;

    @Autowired
    FabricUtil fabricUtil;

    @Autowired
    MyMlccProductInfoMapper productInfoMapper;

    @Autowired
    MyMlccCategoryInfoMapper categoryInfoMapper;

    @Autowired
    MlccFabricInfoMapper fabricInfoMapper;

    @Autowired
    MyMlccPaidanOrderCostMapper paidanOrderCostMapper;

    @Autowired
    MyMlccPaidanOrderGongyiMapper paidanOrderGongyiMapper;

    @Autowired
    MyMlccPaidanOrderAfterMapper paidanOrderAfterMapper;

    @Autowired
    TeamOrderAafterTMapper orderAafterTMapper;

    @Autowired
    MySysUserMapper sysUserMapper;

    @Autowired
    IOrderCenterService service;

    @Autowired
    MyTrackingOrderMapper trackingOrderMapper;

    @Autowired
    MyTeamOrderMapper teamOrderMapper;

    @Autowired
    MyMlccSysuserOrderInfoMapper sysuserOrderInfoMapper;

    @Autowired
    MysmallProductMapper smallProductMapper;

    @Autowired
    MyMlccMaterialLibuInfoMapper libuInfoMapper;

    @Autowired
    MyMlccDilinniInfoMapper dilinniInfoMapper;

    @Autowired
    MyMlccButtonsInfoMapper buttonsInfoMapper;

    @Autowired
    MyMlccModuleSmallTemplateMapper smallTemplateMapper;

    @Autowired
    MyContrastColorMapper contrastColorMapper;

    @Autowired
    FontMapper fontMapper;

    @Autowired
    MyLocatiomMapper locatiomMapper;

    @Autowired
    MyEmbroColorMapper fontColorMapper;

    @Autowired
    MyXiaoBodysizeMapper xiaoBodysizeMapper;

    @Autowired
    MyBodySizeMapper bodySizeMapper;

    @Autowired
    MyCustomerDepartMapper departMapper;

    @Autowired
    SingleAndTeamOrderUtil singleUtil;

    @Autowired
    MyCustomeInfoMapper customeInfoMapper;

    @Autowired
    MyMlccSingleOrderInfoMapper singleOrderInfoMapper;

    /**
     * 获取供应商的个订产品列表
     *
     * @param page      分页器
     * @param orderSn   订单编号
     * @param time      派单时间
     * @param orderType 订单类型：0面料订单，1个订订单，2团订订单，3成衣订单
     */
    @Override
    public IPage<MlccSysuserOrderInfo> listFactorySingleOrder(Page<MlccSysuserOrderInfo> page, String orderSn,
                                                              String time, Integer orderType, String enddate) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<MlccSysuserOrderInfo> wrapper = new QueryWrapper<>();
        if (orderSn != null && !"".equals(orderSn)) {
            wrapper.like("order_sn", orderSn);
        }
        if (orderType == 1) {
            wrapper.eq("order_type", 1);
        }
        if (orderType == 2) {
            wrapper.eq("order_type", 2);
        }
        if (time != null && !"".equals(time)) {
            wrapper.ge("create_time", time);
        }
        if (enddate != null && !"".equals(enddate)) {
            enddate = enddate + " 23:59:59";
            wrapper.le("create_time", enddate);
        }
        wrapper.orderByDesc("create_time");
        if (!"admin".equals(user.getUsername())) {
            wrapper.eq("sysuser_id", user.getId());
        }
        IPage<MlccSysuserOrderInfo> iPage = orderFactoryMapper.selectPage(page, wrapper);

        if (iPage != null) {
            List<MlccSysuserOrderInfo> list = iPage.getRecords();
            if (list != null && list.size() > 0) {
                for (MlccSysuserOrderInfo info : list) {
                    // 查询顾客名称
                    MlccSingleOrderInfo singleOrderInfo = singleOrderInfoMapper.selectById(info.getOrderId());
                    if (singleOrderInfo != null) {
                        info.setGukeName(singleOrderInfo.getCustomerName());
                    }

                    // 查询产品的品类
                    MlccProductInfo productInfo = productInfoMapper.selectById(info.getProductId());
                    if (productInfo != null) {
                        String plid = fabricUtil.getpingleiFromProduct(productInfo);
                        MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(plid);
                        if (categoryInfo != null) {
                            info.setPlName(categoryInfo.getCategoryName()).setPlCode(categoryInfo.getCategoryCode());
                        }
                        //查询产品的工艺
                        String gylxid = fabricUtil.getGYLXFromProduct(productInfo);
                        MlccCategoryInfo gylx = categoryInfoMapper.selectById(gylxid);
                        if (gylx != null) {
                            info.setGylx(gylx.getCategoryName());
                        }
                        // 查询产品的版号
                        String bhid = fabricUtil.getBHFromProduct(productInfo);
                        MlccCategoryInfo bh = categoryInfoMapper.selectById(bhid);
                        if (bh != null) {
                            info.setBhName(bh.getCategoryName());
                            info.setBhCode(bh.getCategoryCode());
                        }
                        // 查询产品当前状态
                        String i = orderFactoryMapper.productStatus(productInfo.getId());
                        info.setStatusName(i);
                    }
                }
            }
        }
        return iPage;
    }

    /**
     * 加工厂获取产品的面料
     *
     * @param productId 产品id
     */
    @Override
    public List<MlccFabricInfo> productFabric(String productId) {
        MlccProductInfo info = productInfoMapper.selectById(productId);
        // 用来保存所有的面料
        ArrayList<MlccFabricInfo> fabricInfos = new ArrayList<>();
        if (info != null) {
            // 拿到产品的面料
            String fabricIds = info.getFabricIds();
            if (fabricIds != null) {
                String[] idAandMishu = fabricIds.split(",");
                if (idAandMishu != null && idAandMishu.length > 0) {
                    for (String fabricidmishu : idAandMishu) {
                        String[] split = fabricidmishu.split("/");
                        MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(split[0]);
                        if (fabricInfo != null) {
                            fabricInfo.setMishu(split[1]);
                            if (split[1] != null) {
                                if (fabricInfo.getFabricPrice() == null && fabricInfo.getGroupId() != null) {
                                    // 获取面料的价格
                                    fabricUtil.addPrice(fabricInfo, Double.valueOf(split[1]));
                                }
                                fabricInfo.setAllPrice(fabricInfo.getFabricPrice().doubleValue() * Double.valueOf(split[1]))
                                        .setJiesuanMpney(info.getFabricSettleMoney().doubleValue()).setJiesuan(info.getIsDuizhang())
                                        .setCreateTime(info.getCreateTime());
                                fabricInfos.add(fabricInfo);
                            }
                        }
                    }
                }
            }
        }
        return fabricInfos;
    }

    /**
     * 加工厂获取产品的加价成本
     *
     * @param page      分页器
     * @param productId 产品id
     */
    @Override
    public IPage<MlccPaidanOrderCost> listjaijaiChengbe(Page<MlccPaidanOrderCost> page, String productId) {
        QueryWrapper<MlccPaidanOrderCost> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productId);
        return paidanOrderCostMapper.selectPage(page, wrapper);
    }

    /**
     * 获取订单下的工艺成本
     *
     * @param page      分页器
     * @param productId 产品id
     */
    @Override
    public IPage<MlccPaidanOrderGongyi> getGYCB(Page<MlccPaidanOrderGongyi> page, String productId) {
        QueryWrapper<MlccPaidanOrderGongyi> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productId);
        IPage<MlccPaidanOrderGongyi> iPage = paidanOrderGongyiMapper.selectPage(page, wrapper);
        List<MlccPaidanOrderGongyi> records = iPage.getRecords();
        if (records != null && records.size() > 0) {
            for (MlccPaidanOrderGongyi record : records) {
                MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(record.getCategoryId());
                if (categoryInfo != null) {
                    record.setGyname(categoryInfo.getCategoryName());
                }
            }
        }
        return iPage;
    }

    /**
     * 获取订单下的返修成本 (个订与团订通用)
     *
     * @param page      分页器
     * @param productId 产品id
     */
    @Override
    public IPage<MlccPaidanOrderAfter> getFanxiuCB(Page<MlccPaidanOrderAfter> page, String productId) {
        QueryWrapper<MlccPaidanOrderAfter> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productId).eq("status", 0);
        return paidanOrderAfterMapper.selectPage(page, wrapper);
    }

    /**
     * 获取团订下的所有产品（大产品）
     *
     * @param orderSn 订单编号
     */
    @Override
    public List<MyteamPriceProduct> listTeamPro(String orderSn) {
        ArrayList<MlccProductInfo> productInfos = new ArrayList<>();
        // 得到团订订单下的所有小产品，分组为大产品
        List<MyteamPriceProduct> products = orderAafterTMapper.listpriceProduuct(orderSn);
        if (products != null && products.size() > 0) {
            for (MyteamPriceProduct product : products) {
                // 拿到产品
                MlccProductInfo info = productInfoMapper.selectById(product.getId());
                // 查询产品的品类
                String plid = fabricUtil.getpingleiFromProduct(info);
                MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(plid);
                if (categoryInfo != null) {
                    product.setPingleiName(categoryInfo.getCategoryName());
                }
                // 查询产品对应的供应商，并赋值给状态
                if (info.getGysId() != null) {
                    MySysUser sysUser = sysUserMapper.selectById(info.getGysId());
                    if (sysUser != null) {
                        product.setGysName(sysUser.getRealname());
                    }
                }
            }
        }
        return products;
    }

    /**
     * 团订派单
     *
     * @param orderSn 订单编号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int teamPaidan(String orderSn) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 团订下的大产品是否已近全部选择供应商？
        // 得到团订订单下的所有小产品，分组为大产品
        List<MyteamPriceProduct> products = orderAafterTMapper.listpriceProduuct(orderSn);
        if (products != null && products.size() > 0) {
            for (MyteamPriceProduct product : products) {
                // 拿到产品
                MlccProductInfo info = productInfoMapper.selectById(product.getId());
                if (info.getGysId() == null || "".equals(info.getGysId())) return -1;
            }
            for (MyteamPriceProduct product : products) {
                // 拿到产品
                MlccProductInfo info = productInfoMapper.selectById(product.getId());
                // 向供应商派单表添加记录
                addPaidan(info, orderSn);
                // 团订插入加价成本项
                service.savePaidanChengbenTean(orderSn, info.getGysId());
                // 团订插入工艺成本
                service.savePaidanGYTeam(orderSn, info.getGysId());
                // 向派单表添加记录

            }
        }
        // 将订单变为以接单状态
        changeStatus(orderSn);
        // 订单跟踪表添加记录
        // 0未支付，1已支付，2申请售后，3已接单，4已发货，5已完成，6备库 7驳回
        addtrackingOrder(orderSn, 2, "订单已接单", user.getRealname(), 3, "平台派单");
        return 1;
    }

    /**
     * 团订-加工厂：大产品下小产品列表
     *
     * @param page        分页器
     * @param productId   大产品id
     * @param productType 小产品类型 0团订，1标准码
     */
    @Override
    public IPage<MlccCustomerProductInfo> listSmallProByProduct(Page<MlccCustomerProductInfo> page, String productId, Integer productType) {
        // 查询大产品下所有小产品
        QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productId);
        if (productType != null && productType == 0) {
            wrapper.eq("bodys_type", 0);
        } else if (productType != null && productType == 1) {
            wrapper.eq("bodys_type", 1);
        }
        // 拿到了名下所有小产品
        IPage<MlccCustomerProductInfo> iPage = smallProductMapper.selectPage(page, wrapper);
        List<MlccCustomerProductInfo> list = iPage.getRecords();
        // 遍历小产品
        if (list != null && list.size() > 0) {
            for (MlccCustomerProductInfo smallpro : list) {
                // 拿到大产品信息
                MlccProductInfo productInfo = productInfoMapper.selectById(smallpro.getProductId());
                if (productInfo != null) {
                    smallpro.setProductName(productInfo.getProductName());
                    String s = fabricUtil.getpingleiFromProduct(productInfo);
                    MlccCategoryInfo mlccCategoryInfo = categoryInfoMapper.selectById(s);
                    if (mlccCategoryInfo != null) {
                        smallpro.setPlName(mlccCategoryInfo.getCategoryName());
                        smallpro.setPingleiCode(mlccCategoryInfo.getCategoryCode());
                    }
                }
            }
        }
        return iPage;
    }

    /**
     * 加工厂小产品详情
     *
     * @param productId 产品ID
     * @param small     小产品id
     */
    @Override
    public MlccProductInfo getDetail(String productId, String small) {
        MlccProductInfo productInfo = productInfoMapper.selectById(productId);
        if (productInfo != null) {

            // 获取小产品对应的员工信息
            MlccCustomerProductInfo smallPro = smallProductMapper.selectById(small);
            if (smallPro != null) {
                MlccCustomerInfo customerInfo = customeInfoMapper.selectById(smallPro.getCustomerId());
                if (customerInfo != null) {
                    productInfo.setCustomerName(customerInfo.getCustomerName()).setSmallCode(customerInfo.getCustomerCode());
                }
            }

            /*查询面料信息*/
            if (productInfo.getFabricIds() != null) {
               /* // 这个产品的面料id
                ArrayList<String> fabricid = new ArrayList<>();*/
                String[] split = productInfo.getFabricIds().split(",");
                QueryWrapper<MlccFabricInfo> fabricWrapper = new QueryWrapper<>();
                fabricWrapper.in("id", Arrays.asList(split));
                productInfo.setFabricInfoList(fabricInfoMapper.selectList(fabricWrapper));
            }

            /*查询里布信息*/
            if (productInfo.getLibuId() != null) {
                MlccMaterialLibuInfo libuInfo = libuInfoMapper.selectById(productInfo.getLibuId());
                if (libuInfo != null) {
                    productInfo.setLibuName(libuInfo.getLibuCode());
                }
            }

            /*查询低领尼信息*/
            if (productInfo.getDilinliId() != null) {
                MlccDilinniInfo dilinniInfo = dilinniInfoMapper.selectById(productInfo.getDilinliId());
                if (dilinniInfo != null) {
                    productInfo.setDilinniName(dilinniInfo.getDilinniNumber());
                }
            }

            /*查询纽扣信息*/
            if (productInfo.getButtonsIds() != null) {
                MlccButtonsInfo buttonsInfo = buttonsInfoMapper.selectById(productInfo.getButtonsIds());
                if (buttonsInfo != null) {
                    productInfo.setButtonName(buttonsInfo.getButtonsName());
                }
            }

            /*查询款式与工艺*/
            if (productInfo.getCategoryIds() != null) {
                String[] split = productInfo.getCategoryIds().split(",");
                QueryWrapper<MlccCategoryInfo> categoryWrapper = new QueryWrapper<>();
                categoryWrapper.in("id", Arrays.asList(split));
                List<MlccCategoryInfo> categoryInfos = categoryInfoMapper.selectList(categoryWrapper);
                for (MlccCategoryInfo info : categoryInfos) {
                    if (info != null) {
                        MlccModuleSmallTemplate smallTemplate = smallTemplateMapper.selectById(info.getParentId());
                        if (smallTemplate != null) {
                            info.setSmallTemplateName(smallTemplate.getParameter());
                        }
                    }
//                    info.setSmallTemplateName(smallTemplateMapper.selectById(info.getParentId()).getParameter());
                }
                productInfo.setCategoryInfo(categoryInfos);
            }
            /*查询撞色数据*/
            if (productInfo.getZhuangseIds() != null) {
                List<MlccContrastcolorInfo> contrastcolorInfos = new ArrayList<>();
                String[] split = productInfo.getZhuangseIds().split(",");
                if (split != null && split.length > 0) {
                    for (String idAndColorName : split) {
                        // 拿到具体的撞色id和颜色名称
                        String[] split1 = idAndColorName.split("/");
                        MlccContrastcolorInfo info = contrastColorMapper.selectById(split1[0]);
                        if (info != null) {
                            info.setColorName(split1[1]);
                            contrastcolorInfos.add(info);
                        }
                    }
                }
                productInfo.setContrastcolorList(contrastcolorInfos);
            }

            // 查询绣字字体
            if (productInfo.getXiuziZiti() != null) {
                MlccEmbroideredFont font = fontMapper.selectById(productInfo.getXiuziZiti());
                if (font != null) {
                    productInfo.setXiuziZiti(font.getEmbroideredName());
                }
            }

            // 查询绣字部位
            if (productInfo.getXiuziWeizhi() != null) {
                MlccCategoryLocaltion localtion = locatiomMapper.selectById(productInfo.getXiuziWeizhi());
                if (localtion != null) {
                    productInfo.setXiuziWeizhi(localtion.getXiuziLocaltion());
                }
            }

            // 查询绣字颜色
            if (productInfo.getXiuziColor() != null) {
                MlccEmbroideredColor color = fontColorMapper.selectById(productInfo.getXiuziColor());
                if (color != null) {
                    productInfo.setXiuziColor(color.getColorName());
                }
            }
        }
        return productInfo;
    }

    /**
     * 团订获取人员尺寸
     *
     * @param proID 小产品id
     */
    @Override
    public List<MlccXiaoProductBodysize> listSmallSize(String proID) {
        QueryWrapper<MlccXiaoProductBodysize> wrapper = new QueryWrapper<>();
        wrapper.eq("customer_product_id", proID).eq("isfanxiu", 0);
        List<MlccXiaoProductBodysize> list = xiaoBodysizeMapper.selectList(wrapper);
        for (MlccXiaoProductBodysize bodysize : list) {
            MlccBodySizeInfo sizeInfo = bodySizeMapper.selectById(bodysize.getBodysizeId());
            bodysize.setBodySizename(sizeInfo.getBodySizename()).setUnit(sizeInfo.getUnit());
        }
        return list;
    }

    /**
     * 根据小产品id获取部门详情
     *
     * @param smallproid 小产品id
     */
    @Override
    public MlccCustomerDepart departmentDetailFromSmallPro(String smallproid) {
        MlccCustomerDepart depart = null;
        MlccCustomerProductInfo productInfo = smallProductMapper.selectById(smallproid);
        if (productInfo != null) {
            depart = departMapper.selectById(productInfo.getDepartId());
        }
        return depart;
    }


    /*------------工具方法-------------*/

    /**
     * 往订单跟踪表添加数据
     *
     * @param orderSn     订单编号
     * @param orderType   订单类型
     * @param remark      备注
     * @param username    更新人
     * @param orderStatus 0未支付，1已支付，2申请售后，3已接单，4已发货，5已完成，6备库
     */
    public void addtrackingOrder(String orderSn, int orderType, String remark, String username, Integer orderStatus, String thing) {
        MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
        trackingOrder.setOrderSn(orderSn).setOrderType(orderType).setRemark(remark)
                .setThing(thing)
                .setCreateBy(username).setUpdateBy(username).setOrderStatus(orderStatus);
        trackingOrderMapper.insert(trackingOrder);
    }

    /**
     * 改变订单状态
     *
     * @param orderSn 订单编号
     */
    public int changeStatus(String orderSn) {
        QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccTeamOrderInfo teamOrderInfo = teamOrderMapper.selectOne(wrapper);
        if (teamOrderInfo != null) {
            teamOrderInfo.setStatus(3);
            int i = teamOrderMapper.updateById(teamOrderInfo);
            if (i > 0) {
                // 出库申请表添加记录
                singleUtil.addChuku(orderSn, 2);
            }
            return i;
        } else {
            return 0;
        }
    }

    /**
     * 团订添加派单记录
     *
     * @param productInfo 产品对象
     * @param orderSn     订单编号
     */
    public int addPaidan(MlccProductInfo productInfo, String orderSn) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccTeamOrderInfo orderInfo = teamOrderMapper.selectOne(wrapper);
        MlccSysuserOrderInfo info = new MlccSysuserOrderInfo();
        info.setSysuserId(productInfo.getGysId()).setProductId(productInfo.getId())
                .setOrderId(orderInfo.getId() + "").setOrderSn(orderSn).setOrderType(2)
                .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
        return sysuserOrderInfoMapper.insert(info);
    }
}
